package com.fabriciojf.action;

import com.fabriciojf.controller.Action;
import com.fabriciojf.persistence.JpaPersistence;
import com.fabriciojf.persistence.JpaUtil;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Action
 *
 * @author Fabricio S Costa fabriciojf@gmail.com
 * @since 01/12/2009
 * @version 1.0
 */
public class DeletarObjetoAction implements Action {

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String nomeClass = request.getParameter("classe");
        try {
            Class classe = Class.forName("com.fabriciojf.model." + nomeClass);
            Object objeto = classe.newInstance();

            RequestDispatcher rd = null;
            objeto = JpaUtil.getEntityManager().find(Class.forName("com.fabriciojf.model." + nomeClass), id);
            JpaPersistence.getInstance().remove(objeto);

            rd = request.getRequestDispatcher("./sucesso.jsp");
            rd.forward(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(CrudRedirectAction.class.getName()).log(Level.SEVERE, null, ex);
            response.sendRedirect("./erro.jsp?erro=" + ex.getMessage());
        } catch (InstantiationException ex) {
            Logger.getLogger(CrudRedirectAction.class.getName()).log(Level.SEVERE, null, ex);
            response.sendRedirect("./erro.jsp?erro=" + ex.getMessage());
        } catch (IllegalAccessException ex) {
            Logger.getLogger(CrudRedirectAction.class.getName()).log(Level.SEVERE, null, ex);
            response.sendRedirect("./erro.jsp?erro=" + ex.getMessage());
        } catch (ServletException ex) {
            Logger.getLogger(DeletarObjetoAction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
